<template>
  <view class="chat-list-component">
    <!-- 如果聊天列表为空 -->
    <view v-if="sessionList.length === 0 && !loading" class="message-empty-box">
      <image class="message-empty-image"
             src="https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/message-empty.png"
             mode="scaleToFill"/>
      <view class="fs-28 fw-600">暂无私信</view>
    </view>

    <!-- 聊天会话列表 -->
    <view v-else class="w-100 ping-30">
      <view
          class="flex-dir-row ali-item-sta flex-x-bet mb-30 bac-col-f br-20 ping-20 session-item"
          v-for="session in sessionList"
          :key="session.id"
          @click="openChat(session)"
      >
        <view class="flex-dir-row ali-item-sta flex-1">
          <view class="pos-rela flex-shrink-0">
            <qmy-gender-border
                iconWidth="15rpx"
                iconHeight="15rpx"
                iconSize="12rpx"
                iconLineHeight="15rpx"
                :gender="getOtherUserGender(session)"
                :avatar="getOtherUserAvatar(session)"
                :avatarWidth="90 + 'rpx'"
                :avatarHeight="90 + 'rpx'"
            />
            <!-- 未读消息红点 -->
            <view
                v-if="getUnreadCount(session) > 0"
                class="unread-dot"
            >
              <text v-if="getUnreadCount(session) <= 99" class="unread-text">
                {{ getUnreadCount(session) }}
              </text>
              <view v-else class="iconfont ic-dian unread-text"></view>
            </view>
          </view>
          <view class="ml-20 flex-1 flex-dir-col">
            <view class="fs-30 fw-600 mb-10">{{ getOtherUserName(session) }}</view>
            <view class="fs-26 col-87 text-element-2">
              {{ formatLastMessage(session.lastMessage) }}
            </view>
          </view>
        </view>
        <view class="fs-24 col-b1 ml-20">{{ formatTime(session.lastMessageTime) }}</view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-load-more status="loading"/>
    </view>
  </view>
</template>

<script>
export default {
  name: 'ChatListComponent',
  props: {
    // 是否可见（用于性能优化）
    isVisible: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      sessionList: [],
      loading: false,
      currentUser: null
    }
  },

  watch: {
    isVisible(val) {
      if (val) {
        this.init()
      }
    }
  },

  mounted() {
    this.init()
  },

  onUnload() {
    // 移除事件监听
    uni.$off('chat-sessions-updated', this.handleSessionsUpdated)
    uni.$off('chat-new-message', this.handleNewMessage)
    uni.$off('chat-unread-count-changed', this.handleUnreadCountChanged)
  },
  onShow() {
    this.init()
  },

  methods: {
    async init() {
      // 获取当前用户信息
      this.currentUser = uni.getStorageSync('userInfo')

      // 监听聊天相关事件
      uni.$on('chat-sessions-updated', this.handleSessionsUpdated)
      uni.$on('chat-new-message', this.handleNewMessage)
      uni.$on('chat-unread-count-changed', this.handleUnreadCountChanged)

      // 加载会话列表
      await this.loadSessions()
    },

    async loadSessions() {
      try {
        this.loading = true
        console.log('ChatListComponent: 开始加载会话列表')

        // 如果聊天管理器存在，让它重新加载会话列表
        if (this.$chat) {
          console.log('ChatListComponent: 通过聊天管理器加载会话')
          await this.$chat.loadSessions()
          // loadSessions方法会触发 chat-sessions-updated 事件，handleSessionsUpdated会处理
        } else {
          // 如果聊天管理器不存在，直接从API加载
          console.log('ChatListComponent: 直接从API加载会话')
          const chatApi = require('@/api/chat.js').default
          const response = await chatApi.getUserSessions()
          if (response.data.code === 200) {
            this.sessionList = response.data.data || []
            console.log('ChatListComponent: 直接加载会话成功:', this.sessionList.length, '个')
            console.log('ChatListComponent: 会话数据:', this.sessionList)
          } else {
            console.error('ChatListComponent: 直接加载会话失败:', response)
          }
        }

      } catch (error) {
        console.error('ChatListComponent: 加载会话列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    handleSessionsUpdated(updatedSessionList) {
      console.log('收到会话更新事件，更新的会话数量:', updatedSessionList.length)
      console.log('当前会话列表数量:', this.sessionList.length)

      // 如果更新的列表为空或数量明显少于当前列表，可能是异常情况，不进行完全替换
      if (updatedSessionList.length === 0 && this.sessionList.length > 0) {
        console.warn('收到空的会话列表更新，忽略此次更新')
        return
      }

      // 如果当前列表为空，直接使用更新的列表
      if (this.sessionList.length === 0) {
        console.log('当前列表为空，直接使用更新的列表')
        this.sessionList = [...updatedSessionList]
      } else {
        // 智能合并：更新已存在的会话，添加新的会话
        console.log('智能合并会话列表')
        this.mergeSessionList(updatedSessionList)
      }

      // 强制重新渲染
      this.$forceUpdate()

      // 通知父组件未读消息数变化
      const unreadCount = this.getTotalUnreadCount()
      this.$emit('unreadCountChange', unreadCount)
    },

    // 智能合并会话列表
    mergeSessionList(updatedSessionList) {
      console.log('开始合并会话列表，更新数量:', updatedSessionList.length)

      const updatedSessionMap = new Map()

      // 将更新的会话列表转换为Map，便于查找
      updatedSessionList.forEach(session => {
        updatedSessionMap.set(String(session.id), session)
      })

      let hasUpdated = false

      // 更新现有会话
      this.sessionList.forEach((session, index) => {
        const updatedSession = updatedSessionMap.get(String(session.id))
        if (updatedSession) {
          console.log('更新现有会话:', session.id)
          // 直接使用新的会话数据
          this.sessionList[index] = {
            ...updatedSession
          }
          updatedSessionMap.delete(String(session.id)) // 标记为已处理
          hasUpdated = true
        }
      })

      // 添加新的会话到列表顶部
      const newSessions = Array.from(updatedSessionMap.values())
      if (newSessions.length > 0) {
        console.log('添加新会话:', newSessions.length, '个')
        this.sessionList.unshift(...newSessions)
        hasUpdated = true
      }

      // 如果有更新，重新排序
      if (hasUpdated) {
        // 按最后消息时间排序
        this.sessionList.sort((a, b) => {
          const timeA = new Date(a.lastMessageTime || a.updateTime || 0)
          const timeB = new Date(b.lastMessageTime || b.updateTime || 0)
          return timeB - timeA
        })
        console.log('会话列表排序完成')
      }

      console.log('会话列表合并完成，最终数量:', this.sessionList.length)
    },

    handleNewMessage(messageData) {
      // 会话列表会通过 handleSessionsUpdated 自动更新
      // 强制重新渲染以确保UI更新
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },

    handleUnreadCountChanged(unreadCount) {
      // 通知父组件未读消息数变化
      this.$emit('unreadCountChange', unreadCount)
    },

    /**
     * 打开聊天页面
     */
    openChat(session) {
      const otherUserId = this.getOtherUserId(session)
      uni.navigateTo({
        url: `/pages/chat/chatDetail?sessionId=${session.id}&targetUserId=${otherUserId}&targetUserAvatar=${session.otherUserAvatar}&targetUserName=${session.otherUserNickname}`
      })
    },

    /**
     * 获取对方用户ID
     */
    getOtherUserId(session) {
      // 新数据结构直接提供了otherUserId
      if (session.otherUserId) {
        return session.otherUserId
      }
      
      // 兼容旧数据结构
      if (!this.currentUser) return null
      return session.user1Id === this.currentUser.id ? session.user2Id : session.user1Id
    },

    /**
     * 获取对方用户名称
     */
    getOtherUserName(session) {
      // 新数据结构直接提供了otherUserNickname
      if (session.otherUserNickname) {
        return session.otherUserNickname
      }
      
      // 兼容旧数据结构
      if (!this.currentUser) return '未知用户'

      if (session.user1Id === this.currentUser.id) {
        return session.user2Name || session.user2Nickname || `用户${session.user2Id}`
      } else {
        return session.user1Name || session.user1Nickname || `用户${session.user1Id}`
      }
    },

    /**
     * 获取对方用户头像
     */
    getOtherUserAvatar(session) {
      const defaultAvatar = 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'
      
      // 新数据结构直接提供了otherUserAvatar
      if (session.otherUserAvatar) {
        return session.otherUserAvatar
      }
      
      // 兼容旧数据结构
      if (!this.currentUser) return defaultAvatar

      if (session.user1Id === this.currentUser.id) {
        return session.user2Avatar || defaultAvatar
      } else {
        return session.user1Avatar || defaultAvatar
      }
    },

    /**
     * 获取对方用户性别
     */
    getOtherUserGender(session) {
      // 新数据结构暂时没有性别信息，使用默认值
      if (session.otherUserGender !== undefined) {
        return session.otherUserGender
      }
      
      // 兼容旧数据结构
      if (!this.currentUser) return 0

      if (session.user1Id === this.currentUser.id) {
        return session.user2Gender || 0
      } else {
        return session.user1Gender || 0
      }
    },

    /**
     * 获取未读消息数
     */
    getUnreadCount(session) {
      // 新数据结构直接提供了unreadCount
      if (session.unreadCount !== undefined) {
        return session.unreadCount
      }
      
      // 兼容旧数据结构
      if (!this.currentUser) return 0

      if (session.user1Id === this.currentUser.id) {
        return session.user1UnreadCount || 0
      } else {
        return session.user2UnreadCount || 0
      }
    },

    /**
     * 获取总未读消息数
     */
    getTotalUnreadCount() {
      return this.sessionList.reduce((total, session) => {
        return total + this.getUnreadCount(session)
      }, 0)
    },

    /**
     * 格式化最后一条消息
     */
    formatLastMessage(lastMessage) {
      if (!lastMessage) return '暂无消息'

      // 如果是媒体消息，显示对应的提示文字
      if (lastMessage.includes('[图片]')) return '[图片]'
      if (lastMessage.includes('[语音]')) return '[语音]'
      if (lastMessage.includes('[视频]')) return '[视频]'
      if (lastMessage.includes('[文件]')) return '[文件]'

      // 文本消息，限制长度
      return lastMessage.length > 20 ? lastMessage.substring(0, 20) + '...' : lastMessage
    },

    /**
     * 格式化时间
     */
    formatTime(timeString) {
      if (!timeString) return ''

      try {
        const time = new Date(timeString)
        const now = new Date()
        const diff = now - time

        // 一分钟内
        if (diff < 60 * 1000) {
          return '刚刚'
        }

        // 一小时内
        if (diff < 60 * 60 * 1000) {
          return Math.floor(diff / (60 * 1000)) + '分钟前'
        }

        // 今天
        if (time.toDateString() === now.toDateString()) {
          return time.getHours().toString().padStart(2, '0') + ':' +
              time.getMinutes().toString().padStart(2, '0')
        }

        // 昨天
        const yesterday = new Date(now)
        yesterday.setDate(yesterday.getDate() - 1)
        if (time.toDateString() === yesterday.toDateString()) {
          return '昨天'
        }

        // 一周内
        if (diff < 7 * 24 * 60 * 60 * 1000) {
          const days = ['日', '一', '二', '三', '四', '五', '六']
          return '周' + days[time.getDay()]
        }

        // 超过一周
        return (time.getMonth() + 1) + '/' + time.getDate()

      } catch (error) {
        console.error('时间格式化失败:', error)
        return ''
      }
    },

    /**
     * 刷新会话列表
     */
    async refresh() {
      await this.loadSessions()
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-list-component {
  width: 100%;
}

.message-empty-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
}

.message-empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.session-item {
  transition: background-color 0.2s;

  &:active {
    background-color: #f8f8f8 !important;
  }
}

.unread-dot {
  position: absolute;
  top: -5rpx;
  right: -5rpx;
  min-width: 30rpx;
  height: 30rpx;
  background-color: #ff4444;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid #ffffff;
}

.unread-text {
  color: #ffffff;
  font-size: 20rpx;
  font-weight: 600;
  line-height: 1;
}

.loading-container {
  padding: 40rpx 20rpx;
  text-align: center;
}

/* 继承父页面的样式类 */
.w-100 {
  width: 100%;
}

.ping-30 {
  padding: 30rpx;
}

.flex-dir-row {
  display: flex;
  flex-direction: row;
}

.flex-dir-col {
  display: flex;
  flex-direction: column;
}

.ali-item-sta {
  align-items: flex-start;
}

.ali-item-cen {
  align-items: center;
}

.flex-x-bet {
  justify-content: space-between;
}

.flex-1 {
  flex: 1;
}

.flex-shrink-0 {
  flex-shrink: 0;
}

.pos-rela {
  position: relative;
}

.pos-abso {
  position: absolute;
}

.bac-col-f {
  background-color: #ffffff;
}

.br-20 {
  border-radius: 20rpx;
}

.br-200 {
  border-radius: 50%;
}

.mb-30 {
  margin-bottom: 30rpx;
}

.mb-10 {
  margin-bottom: 10rpx;
}

.ml-20 {
  margin-left: 20rpx;
}

.fs-30 {
  font-size: 30rpx;
}

.fs-28 {
  font-size: 28rpx;
}

.fs-26 {
  font-size: 26rpx;
}

.fs-24 {
  font-size: 24rpx;
}

.fw-600 {
  font-weight: 600;
}

.col-87 {
  color: #878787;
}

.col-b1 {
  color: #b1b1b1;
}

.text-element-2 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>
